package com.sxhnpg.util;

import java.sql.Connection;


import org.apache.commons.dbcp.BasicDataSourceFactory;

import sun.print.resources.serviceui;

import java.util.Properties;

import javax.sql.DataSource;

public class DBUtil {

	private static ThreadLocal<Connection> local=new ThreadLocal<Connection>();
	private static DataSource ds;
	
	static{
		try{
			Properties properties=new Properties();
			properties.load(DBUtil.class.getClassLoader().getResourceAsStream("mysql.properties"));
			ds=BasicDataSourceFactory.createDataSource(properties);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static Connection getConnection()throws Exception{
		Connection connection=local.get();
		if(connection==null){
			connection=ds.getConnection();
			local.set(connection);
		}
		return connection;
	}
	
	public static void closeConnection()throws Exception{
		Connection connection=local.get();
		local.set(null);
		if(connection!=null){
			connection.close();
		}
	}
	public static void main(String[] args) {
		try{
		Connection connection1=getConnection();
		Connection connection2=getConnection();
		System.out.println(connection1);
		System.out.println(connection2);
		System.out.println(connection1==connection2);
		}catch (Exception e) {
			e.printStackTrace();
		}
	}
}
